package com.zym.init.controller.backend;

import com.zym.init.core.annotation.ApiBackendRestController;
import com.zym.init.core.annotation.Log;
import com.zym.init.core.controller.BaseController;
import com.zym.init.core.domain.AjaxResult;
import com.zym.init.core.exception.ServiceException;
import com.zym.init.model.query.RoleQuery;
import com.zym.init.service.RoleService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.zym.init.core.constant.CommonConstant.FORBIDDEN_OPERATION_ROLE_IDS;
import static com.zym.init.core.constant.CommonConstant.ONLY_ALLOW_MODIFY_PERMISSION_ROLE_IDS;

@Validated
@ApiBackendRestController
@RequestMapping(path = "/role", produces = "application/json")
public class RoleController extends BaseController {

    final private RoleService roleService;

    public RoleController(RoleService roleService) {
        this.roleService = roleService;
    }

    /**
     * 获取角色列表
     */
    @Log(title = "获取角色列表")
    @PreAuthorize("@ss.hasPermission('system:role:list')")
    @GetMapping
    public AjaxResult list(RoleQuery query) {
        return success("获取成功", roleService.getPage(query));
    }

    /**
     * 新增角色
     */
    @Log(title = "新增角色")
    @PreAuthorize("@ss.hasPermission('system:role:add')")
    @PostMapping
    public AjaxResult add(@RequestBody @Validated(value = {RoleQuery.Add.class}) RoleQuery query) {
        return roleService.add(query) ? success("新增成功") : fail("新增失败");
    }

    /**
     * 编辑角色
     */
    @Log(title = "编辑角色")
    @PreAuthorize("@ss.hasPermission('system:role:edit')")
    @PutMapping
    public AjaxResult edit(@RequestBody @Validated(value = {RoleQuery.Update.class}) RoleQuery query) {
        return roleService.edit(query) ? success("编辑成功") : fail("编辑失败");
    }

    /**
     * 删除角色
     */
    @Log(title = "删除角色")
    @PreAuthorize("@ss.hasPermission('system:role:delete')")
    @DeleteMapping
    public AjaxResult delete(@RequestParam("ids") List<Long> ids) {
        List<Long> forbiddenDeleteRoleIds = new ArrayList<>();
        forbiddenDeleteRoleIds.addAll(Arrays.stream(FORBIDDEN_OPERATION_ROLE_IDS).toList());
        forbiddenDeleteRoleIds.addAll(Arrays.stream(ONLY_ALLOW_MODIFY_PERMISSION_ROLE_IDS).toList());
        for (Long id : forbiddenDeleteRoleIds) {
            if (ids.contains(id)) {
                throw new ServiceException("不能删除系统默认角色");
            }
        }
        if (roleService.isRoleCodeUsed(ids)) {
            throw new ServiceException("您删除的角色中存在已分配的角色，请先解除分配后，再尝试删除");
        }
        return roleService.removeBatchByIds(ids) ? success("删除成功") : fail("删除失败");
    }

}
